import pygame
import random
import numpy as np

# 初始化pygame
pygame.init()

# 迷宫的宽度和高度
width, height = 800, 600

# 设置屏幕
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("迷宫游戏")

# 游戏变量
running = True
fps = 30
block_size = 75
maze_width, maze_height = 10, 8
current_pos = [0, 0]

# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
grey = (200, 200, 200)

# 生成迷宫边缘
def make_maze_edges():
    edges = np.zeros((maze_height, maze_width))
    edges[0, :], edges[-1, :], edges[:, 0], edges[:, -1] = 1, 1, 1, 1
    return edges

# 生成棋盘边界
def make_board_edges(maze_width, maze_height):
    edges = np.zeros((maze_height, maze_width), dtype=int)
    for i in range(maze_width):
        # 上边界
        edges[0][i] = i+1
        # 下边界
        edges[-1][i] = (maze_width * 2) + maze_height - 2 - i
    for i in range(1, maze_height - 1):
        # 左边界
        edges[i][0] = (maze_width * 2) + (maze_height * 2) - 2 - i
        # 右边界
        edges[i][-1] = maze_width + i
    return edges
# 绘制边界
def draw_edges(edges):
    font = pygame.font.Font(None, 24)
    for y in range(maze_height):
        for x in range(maze_width):
            rect = pygame.Rect(x * block_size, y * block_size, block_size, block_size)

            # 仅绘制边界上的格子
            if edges[y][x] != 0:
                pygame.draw.rect(win, grey, rect)
                text = font.render(str(edges[y][x]), True, black)
                text_rect = text.get_rect(center=(x * block_size + block_size//2, y * block_size + block_size//2))
                win.blit(text, text_rect)
# 绘制玩家位置
def draw_player():
    pygame.draw.rect(win, green, (current_pos[0] * block_size,
                                  current_pos[1] * block_size,
                                  block_size, block_size))

# 骰子结果显示
def display_dice_result(dice_number):
    font = pygame.font.Font(None, 36)
    text = font.render(f'Dice Roll: {dice_number}', True, black, blue)

    # 设置文本显示位置为左上角紧挨着外圈
    text_rect = text.get_rect(topleft=(block_size, block_size))

    win.blit(text, text_rect)

# 用于选择骰子数量的radio buttons
dice_count_buttons = [pygame.Rect(10 + i*110, height - 70, 100, 50) for i in range(3)]
dice_count_labels = ['1', '2', '3']
selected_dice_count = 1

def draw_dice_count_buttons(selected):
    font = pygame.font.Font(None, 36)
    for i, rect in enumerate(dice_count_buttons):
        color = green if (i+1) == selected else grey
        pygame.draw.rect(win, color, rect)
        label = font.render(dice_count_labels[i], True, white)
        win.blit(label, (rect.x + 40, rect.y + 10))

# 处理骰子数量的选择
def handle_click_dice_count(mouse_pos):
    global selected_dice_count
    for i, rect in enumerate(dice_count_buttons):
        if rect.collidepoint(mouse_pos):
            selected_dice_count = i + 1
            return
# 判断这个位置是否可以走
def can_move_to(maze, x, y):
    return maze[y][x] !=0

# 移动当前位置
# def move_current_pos(maze, dice_number):
#     # 顺时针移动的方向：右下左上
#     directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
#     direction_idx = 0  # 开始方向设置为向右

#     # 寻找开始的方向
#     if current_pos[1] == 1: # 如果在顶行，只能向右或者向下
#         direction_idx = 1 if current_pos[0] == maze_width - 2 else 0
#     elif current_pos[0] == maze_width - 2: # 如果在最右列，只能向下或者向左
#         direction_idx = 2 if current_pos[1] == maze_height - 2 else 1
#     elif current_pos[1] == maze_height - 2: # 如果在最底行，只能向左或者向上
#         direction_idx = 3 if current_pos[0] == 1 else 2
#     elif current_pos[0] == 1: # 如果在最左列，只能向上或者向右
#         direction_idx = 0 if current_pos[1] == 1 else 3

#     while dice_number > 0:
#         next_x = current_pos[0] + directions[direction_idx][0]
#         next_y = current_pos[1] + directions[direction_idx][1]

#         if can_move_to(maze, next_x, next_y):
#             current_pos[0] = next_x
#             current_pos[1] = next_y
#             dice_number -= 1
#         else:  # 如果不能移动到下一个位置，意味着到达了拐角，需要转弯
#             direction_idx = (direction_idx + 1) % 4
# 移动当前位置
def move_current_pos(directions, dice_number):
    global current_pos
    global direction_idx

    # 寻找开始的方向
    if current_pos[1] == 0 and current_pos[0] < maze_width - 1:  # 如果在顶行，只能向右
        direction_idx = 0
    elif current_pos[0] == maze_width - 1 and current_pos[1] < maze_height - 1:  # 如果在最右列，只能向下
        direction_idx = 1
    elif current_pos[1] == maze_height - 1 and current_pos[0] > 0:  # 如果在最底行，只能向左
        direction_idx = 2
    elif current_pos[0] == 0 and current_pos[1] > 0:  # 如果在最左列，只能向上
        direction_idx = 3

    while dice_number > 0:
        next_x = current_pos[0] + directions[direction_idx][0]
        next_y = current_pos[1] + directions[direction_idx][1]

        if can_move_to(edges, next_x, next_y):
            current_pos[0] = next_x
            current_pos[1] = next_y
            dice_number -= 1
        else:  # 到达边界的角落时需要拐弯
            direction_idx = (direction_idx + 1) % 4
# 主循环
# edges = make_maze_edges()
edges = make_board_edges(maze_width, maze_height)
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
dice_number = 0    # 在循环开始之前初始化骰子数量
clock = pygame.time.Clock()
count = 1

need_redraw = True  # 新增变量，用于跟踪是否需要重绘
while running:
    clock.tick(fps)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # 摇骰子
                dice_number = 1 #random.randint(1, selected_dice_count * 3)
                # 将骰子数量处理函数放在这里
                move_current_pos(directions, dice_number)
                print("移动次数:", dice_number)
                need_redraw = True  # 设置标志表示需要重绘

    if need_redraw:
        win.fill(blue)
        draw_edges(edges)
        draw_player()
        draw_dice_count_buttons(selected_dice_count)
        display_dice_result(dice_number)
        pygame.display.update()
        need_redraw = False  # 重置标志，防止连续重绘

pygame.quit()
